<?php
/*
 * Logs
 *
 * Author: Pota
 * Datetime: 16/10/20 下午2:21
 */

namespace Services;

use Symfony\Component\DependencyInjection\ContainerInterface;

class Logs
{
    private $container;

    private $path;

    private $file;

//    private $line;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        if (!$this->isHas()){
            $this->file = fopen($this->path, "w");
            if ($this->container->get('kernel')->getEnvironment() == 'dev')
                chmod($this->path,0777);
        }
    }

    /*
     * 写入
     */
    public function set($content)
    {
        $content = "[" . date('Y-m-d H:i:s', time()) . "] response.INFO:" . $content . "\r\n";
        file_put_contents($this->path, $content, FILE_APPEND);

        return true;
    }

    /*
     * 获取
     */
    public function get($length = 20)
    {
        return $this->tail($this->path, $length);
    }

    /**
     * 文件最后几行
     * @param $file
     * @param $num
     * @return array
     */
    function tail($file,$num){
        $fp = fopen($file,"r");
        $pos = -2;
        $eof = "";
        $head = false;   //当总行数小于Num时，判断是否到第一行了
        $lines = array();
        while($num>0){
            while($eof != "\n"){
                if(fseek($fp, $pos, SEEK_END)==0){    //fseek成功返回0，失败返回-1
                    $eof = fgetc($fp);
                    $pos--;
                }else{                               //当到达第一行，行首时，设置$pos失败
                    fseek($fp,0,SEEK_SET);
                    $head = true;                   //到达文件头部，开关打开
                    break;
                }

            }
            array_unshift($lines,fgets($fp));
            if($head){ break; }                 //这一句，只能放上一句后，因为到文件头后，把第一行读取出来再跳出整个循环
            $eof = "";
            $num--;
        }
        fclose($fp);

        return $lines;
    }

    /**
     * 是否存在
     * @return mixed
     */
    private function isHas()
    {
//        echo date('Y-m-d w', strtotime('last day next week'));
        $this->path = dirname( $this->container->get('kernel')->getRootDir() ) . DIRECTORY_SEPARATOR . '/app/logs/' . $this->container->get('kernel')->getEnvironment()  . '_' . date('Y-m-d', strtotime('this week')) . '.log' ;

        return file_exists ($this->path);
    }
}